<script setup>
import { userRegisterService, userLoginService } from '@/api/user.js'
// 导入图标
import { User, Lock } from '@element-plus/icons-vue'
import { ref, watch } from 'vue'
import { useUserStore } from '@/stores/index.js'
import { useRouter } from 'vue-router'
// 控制注册登录
const isRegister = ref(false)
// 绑定form表单
const form = ref()

// 注册  整个的用于提交的form数据对象
const formModel = ref({
  username: '',
  password: '',
  repassword: ''
})
// 注册  整个表单的验证规则
const rules = {
  username: [
    // 触发校验的时机 trigger:  'blur' 失去焦点的时候校验   'change' 实时校验
    // required: true 非空校验
    { required: true, message: '请输入用户名', trigger: 'blur' },
    // 长度校验
    {
      min: 5,
      max: 10,
      message: '用户名必须是 5-10位 的非空字符',
      trigger: 'blur'
    }
    // 正则校验  pattern：
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    // 正则校验  pattern：
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是 6-15位 的字符',
      trigger: 'blur'
    }
  ],
  repassword: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    // 正则校验  pattern：
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是 6-15位 的字符',
      trigger: 'blur'
    },
    // 自定义校验 validator:(rule, value, callback)
    //  rule 当前校验规则相关的信息
    // value 所校验的表单元素目前的表单
    // callback 无论成功还是失败， 都需要 callback 回调
    //      -callback（）校验成功
    //      -callBACK(new Error(错误信息)) 校验失败
    {
      validator: (rule, value, callback) => {
        if (value !== formModel.value.password) {
          callback(new Error('两次密码输入不一致'))
        } else {
          callback() //就算校验成功， 需要回调callback
        }
      },
      trigger: 'blur'
    }
  ]
}

// 注册按钮
const register = async () => {
  // 注册成功之前 ，先进行校验， 校验成功 -> 发送请求 ，  校验失败-> 自动提示
  // validate	对整个表单的内容进行验证。 接收一个回调函数，或返回 Promise
  await form.value.validate()
  // console.log('开始注册请求')
  const {
    data: { code, message }
  } = await userRegisterService(formModel.value)
  // console.log(res)
  // 注册成功
  if (!code) {
    ElMessage.success(message)
    isRegister.value = false
  }
  // 注册失败
  if (code) {
    ElMessage.success(message)
  }
}

// 登录
const userStore = useUserStore()
const router = useRouter()
const login = async () => {
  // 预校验
  await form.value.validate()
  // console.log('登录请求')
  // 发送请求
  const {
    data: { code, message, token }
  } = await userLoginService(formModel.value)
  // console.log(res)
  // 登录成功
  if (!code) {
    // 存到仓库
    console.log(token)
    userStore.setToken(token)
    ElMessage.success(message)
    // 跳首页
    router.push('/')
  }
  // 登录
  if (code) {
    ElMessage.success(message)
  }
}

watch(isRegister, () => {
  formModel.value = {
    username: '',
    password: '',
    repassword: ''
  }
})
</script>
<template>
  <el-row class="login-page">
    <el-col :span="12" class="bg"></el-col>
    <el-col :span="6" :offset="3" class="form">
      <!-- 注册 -->
      <el-form
        ref="form"
        :model="formModel"
        :rules="rules"
        size="large"
        autocomplete="off"
        v-if="isRegister"
      >
        <el-form-item>
          <h1>注册</h1>
        </el-form-item>
        <!-- 用户名 -->
        <el-form-item prop="username">
          <el-input
            v-model="formModel.username"
            :prefix-icon="User"
            placeholder="请输用户名"
          ></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item prop="password">
          <el-input
            v-model="formModel.password"
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item prop="repassword">
          <el-input
            v-model="formModel.repassword"
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入再次密码"
          ></el-input>
        </el-form-item>
        <!-- 注册按钮 -->
        <el-form-item>
          <el-button
            @click="register"
            class="button"
            type="primary"
            auto-insert-space
          >
            注册
          </el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = false">
            ← 有账号? 去登录
          </el-link>
        </el-form-item>
      </el-form>

      <!-- 登录 -->
      <el-form
        :model="formModel"
        :rules="rules"
        ref="form"
        size="large"
        autocomplete="off"
        v-else
      >
        <el-form-item>
          <h1>登录</h1>
        </el-form-item>
        <el-form-item prop="username">
          <el-input
            v-model="formModel.username"
            :prefix-icon="User"
            placeholder="请输用户名"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="formModel.password"
            name="password"
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item class="flex">
          <div class="flex">
            <el-checkbox>记住我</el-checkbox>
            <el-link type="primary" :underline="false">忘记密码？</el-link>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button
            @click="login()"
            class="button"
            type="primary"
            auto-insert-space
            >登录</el-button
          >
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = true">
            去注册 →
          </el-link>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>
<style lang="scss" scoped>
.login-page {
  height: 100vh;
  background-color: #fff;
  .bg {
    background: url('@/assets/logo.png') no-repeat 60% center / 240px auto,
      url('@/assets/login_bg.jpg') no-repeat center / cover;
    border-radius: 0 20px 20px 0;
  }
  .form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    user-select: none;
    .title {
      margin: 0 auto;
    }
    .button {
      width: 100%;
    }
    .flex {
      width: 100%;
      display: flex;
      justify-content: space-between;
    }
  }
}
</style>
